package com.tender.shiro.filter;

import com.alibaba.fastjson.JSON;
import com.tender.common.Result;
import com.tender.constants.Constants;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import org.apache.shiro.web.util.WebUtils;

public class JwtRolesAuthorizationFilter extends RolesAuthorizationFilter {

    /**
     * 访问拒绝时调用
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        //判断当前请求头中是否带有jwtToken的字符串
        String jwtToken = WebUtils.toHttp(request).getHeader(Constants.AUTHORIZATION_HEADER);
        //如果有：返回json的应答
        if (StringUtils.isNotBlank(jwtToken)) {
            Result<Object> result = Result.of();
            result.setResultCode(Constants.NO_ROLE_AUTHORITY_CODE);
            result.setResultMsg(Constants.NO_ROLE_AUTHORITY_MESSAGE);
            response.setCharacterEncoding(Constants.UTF_8_ENCODING);
            response.setContentType(Constants.CONTENT_TYPE_WITH_UTF_8_AND_JSON);
            response.getWriter().write(JSON.toJSONString(result));
            return false;
        }
        // 如果没有：走原始方式
        return super.onAccessDenied(request, response);
    }
}
